<?php

class User extends AppModel {
	var $name = "User";
	
	var $belongsTo = array('Group');
	
	
    /**
     * Allows the AclBehavior to determine parental ownership of
     * currently active record.
     *
     * @access public
     * @returns array data array to be used by AclBehavior for node lookup
     */
	function parentNode(){
	    if (!$this->id) {
		    return null;
		}

		$data = $this->read();

		if (!$data['User']['group_id']){
		    return null;
		} else {
		    return array('model' => 'Group', 'foreign_key' => $data['User']['group_id']);
		}
    }

	/**
		SEE: http://book.cakephp.org/view/645/Acts-As-a-Requester
		this checks whether a new user is created or 
		updated its new group.
	*/
	function afterSave($created = null){
	    if( $created ){
		    $this->id = $this->getLastInsertId();
		    // first create alias for the newly created Aro
		    // ACL Behavior does NOT manage alias values
		    
			  $aroId = $this->Aro->getLastInsertId();
			$this->Aro->create();
			$this->Aro->id = $aroId;
			if( $this->Aro->saveField('alias', $this->data['User']['username'] ) ){
				return TRUE;
			} else {
				return FALSE;
			}
			
		} else {
            if( isset($this->data['User']['group_id']) && isset( $this->data['User']['old_group_id'] ) ){
				 if( $this->data['User']['group_id'] !== $this->data['User']['old_group_id'] ){
				// what is the id of the aro row that has $this->data['User']['group_id'] as it's foreign_key?
				$groupInfo = $this->Aro->find(array('foreign_key'=>$this->data['User']['group_id'], 'model'=>'Group') );
				$userAro = $this->Aro->find(array('foreign_key'=>$this->data['User']['id'], 'model'=>'User') );
				$updatedAro = array(
					'Aro' => array(
						'id' => $userAro['Aro']['id'],
						'parent_id' => $groupInfo['Aro']['id']
						)
					);
				$this->Aro->save( $updatedAro );
			
				}
			}
		}

	}
	
}

?>